import send_msg from '@feidao-factory/send-msg';
import { RedisClient } from 'redis';
import { get, set } from '../_redis';

interface IError {
	code?: number;
	error?: string;
}

export interface IRole {
	_id: string;
	role_no: string;
	role_name: string;
	pk_val: string;
	role_type_id: string;
	role_type_name: string;
}

export interface IMenu {
	_id: string;
	menu_no: string;
	menu_name: string;
	client_type: string;
	parent_no: string;
	icon: string;
	show_type: string;
	description: string;
	priority: number;
	is_single: boolean;
	is_offline: boolean;
	is_guest: boolean;
	productid: string;
	systemid: string;
	formid: string;
	background: string;
	refsystemid: string;
	formname: string;
	package_no: string;
	package_name: string;
	package_url: string;
	auth_code: number;
}

export interface IUserRoleAndAuthInfo {
	roles: IRole[];
	menus: IMenu[];
	role_no: string;
	usercode: string;
	params?: any;	// todo need fixed
}

export const PREFIX_ROLES = 'ROLE_';

async function get_user_info_and_save_redis(client: RedisClient, actionid: string, sessionid: string, spaceid: string, productid: string, clienttype: string, role_no?: string) {
	// 客户端类型，web:3，h5:2，c#:4，phone:1,pad-native-w:5,pad-native-h:6,pad-h5-w:7,pad-h5-h:8,xcx:9
	const ret = await send_msg<IUserRoleAndAuthInfo | IError>(actionid, sessionid, 'permservice.getuserroleandauthinfo', {
		clienttype,
		productid,
		role_no,
		spaceid,
		systemid: '12'
	});
	const err = ret as IError;
	if ((err.code === undefined) && (err.error === undefined)) {
		const data = ret as IUserRoleAndAuthInfo;
		await set(client, PREFIX_ROLES + spaceid + '_' + sessionid, data);
		return data;
	} else {
		throw new Error('Could not get user auth info:' + err.error);
	}
}

export async function get_use_info(client: RedisClient, actionid: string, sessionid: string, spaceid: string, productid: string, clienttype: string, role_no?: string) {
	const ui = await get<IUserRoleAndAuthInfo>(client, PREFIX_ROLES + spaceid + '_' + sessionid);
	if (ui && (!role_no || ui.role_no === role_no)) {
		return ui;
	} else {
		return await get_user_info_and_save_redis(client, actionid, sessionid, spaceid, productid, clienttype, role_no);
	}
}

